package com.yuzhi.common.core.domain;

import com.yuzhi.common.contant.HttpStatus;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;

/**
 * @Description: 全局统一返回体
 * @Author: sunshine
 * @Date: 2024-02-28
 */
@Data
@NoArgsConstructor
public class ApiResult<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 成功
     */
    public static final int SUCCESS = 200;

    /**
     * 失败
     */
    public static final int FAIL = 500;

    private int code;

    private boolean success;

    private String msg;
    /**
     * 是否认证
     */
    private boolean authenticated;

    private T data;

    public static <T> ApiResult<T> ok() {
        return restResult(null, SUCCESS, "操作成功",true,true);
    }

    public static <T> ApiResult<T> ok(T data) {
        return restResult(data, SUCCESS, "操作成功",true,true);
    }

    public static <T> ApiResult<T> ok(String msg) {
        return restResult(null, SUCCESS, msg,true,true);
    }

    public static <T> ApiResult<T> ok(String msg, T data) {
        return restResult(data, SUCCESS, msg,true,true);
    }

    public static <T> ApiResult<T> fail() {
        return restResult(null, FAIL, "操作失败",false,true);
    }

    public static <T> ApiResult<T> fail(String msg) {
        return restResult(null, FAIL, msg,false,true);
    }

    public static <T> ApiResult<T> fail(T data) {
        return restResult(data, FAIL, "操作失败",false,true);
    }

    public static <T> ApiResult<T> fail(String msg, T data) {
        return restResult(data, FAIL, msg,false,true);
    }

    public static <T> ApiResult<T> fail(int code, String msg) {
        return restResult(null, code, msg,false,true);
    }

    public static <T> ApiResult<T> fail(int code, String msg,boolean authenticated) {
        return restResult(null, code, msg,false,authenticated);
    }

    /**
     * 返回警告消息
     *
     * @param msg 返回内容
     * @return 警告消息
     */
    public static <T> ApiResult<T> warn(String msg) {
        return restResult(null, HttpStatus.WARN, msg,true,true);
    }

    /**
     * 返回警告消息
     *
     * @param msg 返回内容
     * @param data 数据对象
     * @return 警告消息
     */
    public static <T> ApiResult<T> warn(String msg, T data) {
        return restResult(data, HttpStatus.WARN, msg,true,true);
    }

    private static <T> ApiResult<T> restResult(T data, int code, String msg,boolean success,boolean authenticated) {
        ApiResult<T> apiResult = new ApiResult<>();
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMsg(msg);
        apiResult.setSuccess(success);
        apiResult.setAuthenticated(authenticated);
        return apiResult;
    }

    public static <T> Boolean isError(ApiResult<T> ret) {
        return !isSuccess(ret);
    }

    public static <T> Boolean isSuccess(ApiResult<T> ret) {
        return ApiResult.SUCCESS == ret.getCode();
    }
}
